<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>WebRTC capture video and audio</title>
</head>
<body>

<div>
  <label>audio Source</label>
  <select id="audioSource"></select>
</div>
<div>
  <label>audio Output</label>
  <select id="audioOutput"></select>
</div>
<div>
  <label>video Source</label>
  <select id="videoSource"></select>
</div>

<video autoplay playsinline id="player"></video>

<!--https://webrtc.github.io/adapter/adapter-latest.js-->
<!--https://webrtchacks.github.io/adapter/adapter-latest.js-->
<!--https://github.com/webrtchacks/adapter-->
<!--https://www.npmjs.com/package/webrtc-adapter-->
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script>
  // const audioSource = document.querySelector('select#audioSource'); //设置为id 已经自动获取
  // const audioOutput = document.querySelector('select#audioOutput');
  // const videoSource = document.querySelector('select#videoSource');
  const videoplay = document.querySelector('video#player');

  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    console.log('getUserMedia is not supported!');
  }else {
    const MediaStreamConstrains = {
      video: true,
      audio: true
    };

    navigator.mediaDevices.getUserMedia(MediaStreamConstrains)
      .then(gotMediaStream)
      .then(gotDevices)
      //如果在调用getUserMedia的弹窗中点击了拒绝授权, 也会走↓的catch回调
      .catch(handleError);
  }

  function gotMediaStream(stream){
    videoplay.srcObject = stream;
    return navigator.mediaDevices.enumerateDevices();
  }

  function handleError(error){
    console.error('getUserMedia error ---:', error);
  }

  function gotDevices(deviceInfos) {
    deviceInfos.forEach((deviceInfo) => {
      const option = document.createElement('option');
      option.text = deviceInfo.label;
      option.value = deviceInfo.deviceId;

      switch (deviceInfo.kind) {
        case 'audioinput':
          audioSource.appendChild(option);
          break;
        case 'audiooutput':
          audioOutput.appendChild(option);
          break;
        case 'videoinput':
          videoSource.appendChild(option);
      }
    });
  }
</script>
</body>
</html>
